﻿using System.Security.Claims;

namespace net_work.Common;

public interface IUserContext
{
    string Username { get; set;}
    long UserId { get; set; }
    string UserRole { get; set; }
}

public class UserContext(IHttpContextAccessor httpContextAccessor) : IUserContext
{
    // 用于手动设置上下文信息
    private string? _username;
    private long? _userId;
    private string? _userRole;

    public string Username
    {
        get
        {
            if (!string.IsNullOrEmpty(_username))
                return _username;

            return httpContextAccessor.HttpContext?.User.Identity?.Name ??
                   throw new InvalidOperationException("JWT 用户名为空");
        }
        set => _username = value; // 支持手动设置用户名
    }

    public long UserId
    {
        get
        {
            if (_userId.HasValue)
                return _userId.Value;

            return long.Parse(httpContextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value ??
                              throw new InvalidOperationException("JWT 用户ID为空"));
        }
        set => _userId = value; // 支持手动设置用户ID
    }

    public string UserRole
    {
        get
        {
            if (!string.IsNullOrEmpty(_userRole))
                return _userRole;

            return httpContextAccessor.HttpContext?.User.FindFirst(ClaimTypes.Role)?.Value ??
                   throw new InvalidOperationException("JWT 用户角色为空");
        }
        set => _userRole = value; // 支持手动设置用户角色
    }
}